package com.lzx.applib.adapter;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Interpolator;
import android.widget.Scroller;

import com.lzx.applib.utils.LogUtil;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Lzx on 16/11/02 0002.
 */

public abstract class SimpleRecyclePagerAdapter<T, E extends SimpleViewHolder<T>> extends SimplePagerAdapter {

    private static final String TAG = "RecyclePagerAdapter";

    private final ViewPager viewPager;
    private boolean auto = false;
    private long delay = 3000;
    Handler handler;

    Field scrollField;
    Scroller curScroller;
    Scroller fixScroller;

    public SimpleRecyclePagerAdapter(ViewPager viewPager, List<T> data) {
        super(viewPager.getContext(), data);
        this.viewPager = viewPager;
        if (data.size() > 1) {
            List<T> showData = new ArrayList<>(data);
            showData.add(data.get(0));
            showData.add(0, data.get(data.size() - 1));
            this.data = showData;

            viewPager.addOnPageChangeListener(new SimpleOnPageChangeListener());
        }
    }

    public void onPause() {
        changeScroller(curScroller);
        handler.removeMessages(0);
    }

    public void onResume() {
        changeScroller(fixScroller);
        handler.sendEmptyMessageDelayed(0, delay);
    }

    @Override
    public E onCreateViewHolder(ViewGroup parent, int viewType) {
        return null;
    }

    /**调用该方法，则必须在退出时调用onPause、启动时调用onResume*/
    public void autoRecycler(final long delay) {
        if (data.size() <=1 ) return;

        this.delay = delay;
        this.auto = true;

        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                onResume();
                viewPager.setCurrentItem(viewPager.getCurrentItem() + 1, true);
            }
        };

        viewPager.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                onPause();
                if (event.getAction() == MotionEvent.ACTION_UP
                        || event.getAction() == MotionEvent.ACTION_CANCEL) {
                    handler.sendEmptyMessageDelayed(0, delay);
                }
                return false;
            }
        });

        viewPager.addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() {
            @Override
            public void onViewAttachedToWindow(View v) {
                LogUtil.d(TAG, "onViewAttachedToWindow");
                handler.sendEmptyMessageDelayed(0, delay);
                viewPager.requestLayout();
            }

            @Override
            public void onViewDetachedFromWindow(View v) {
                LogUtil.d(TAG, "onViewDetachedFromWindow");
                handler.removeMessages(0);
            }
        });
    }

    private void changeScroller(Scroller scroller) {
        try {
            if (scrollField == null) {
                scrollField = ViewPager.class.getDeclaredField("mScroller");
                scrollField.setAccessible(true);
                curScroller = (Scroller) scrollField.get(viewPager);
                fixScroller = new FixedSpeedScroller(viewPager.getContext(), new AccelerateInterpolator());
            }
            if (scroller == null) {
                scroller = fixScroller;
            }
            scrollField.set(viewPager, scroller);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private class SimpleOnPageChangeListener implements ViewPager.OnPageChangeListener {

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }

        @Override
        public void onPageSelected(int position) {
        }

        @Override
        public void onPageScrollStateChanged(int state) {
            if (state == ViewPager.SCROLL_STATE_IDLE) {
                if (viewPager.getCurrentItem() == 0) {
                    viewPager.setCurrentItem(data.size() - 2, false);
                } else if (viewPager.getCurrentItem() == getCount() - 1) {
                    viewPager.setCurrentItem(1, false);
                }
            }
        }
    }

    private class FixedSpeedScroller extends Scroller {
        private int mDuration = 500;

        public FixedSpeedScroller(Context context) {
            super(context);
        }

        public FixedSpeedScroller(Context context, Interpolator interpolator) {
            super(context, interpolator);
        }

        @Override
        public void startScroll(int startX, int startY, int dx, int dy, int duration) {
            super.startScroll(startX, startY, dx, dy, mDuration);
        }

        @Override
        public void startScroll(int startX, int startY, int dx, int dy) {
            super.startScroll(startX, startY, dx, dy, mDuration);
        }

        public void setmDuration(int time) {
            mDuration = time;
        }

        public int getmDuration() {
            return mDuration;
        }

    }
}
